package com.sec.android.app.myfiles.module.download;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.sec.android.app.myfiles.module.ContentObservable;
import com.sec.android.app.myfiles.module.abstraction.AbsContentObserverImp;
import com.sec.android.app.myfiles.module.abstraction.FileRecord;
import com.sec.android.app.myfiles.module.download.providerapps.AbsContentObserver;
import com.sec.android.app.myfiles.module.download.providerapps.BluetoothObserver;
import com.sec.android.app.myfiles.module.download.providerapps.BrowserObserver;
import com.sec.android.app.myfiles.module.download.providerapps.SimpleShareObserver;
import com.sec.android.app.myfiles.util.JUnitHandler;

import java.util.ArrayList;

public class DownloadObserverImp extends AbsContentObserverImp {
    private ArrayList<AbsContentObserver> mContentObserver;
    private UpdateHandler mUpdateHandler = new UpdateHandler();

    public DownloadObserverImp(Context context, FileRecord record, ContentObservable updater) {
        super(context, record, updater);
    }

    private void createObserver() {
        Handler handler = new Handler();

        mContentObserver = new ArrayList<>();

        if (mContext == null) {
            return;
        }
        mContentObserver.add(new BrowserObserver(handler, mContext, this));
        mContentObserver.add(new BluetoothObserver(handler, mContext, this));
        mContentObserver.add(new SimpleShareObserver(handler, mContext, this));
    }

    @Override
    public void start() {
        createObserver();

        for (AbsContentObserver observer : mContentObserver) {
            observer.register();
        }
    }

    @Override
    public void stop() {
        for (AbsContentObserver observer : mContentObserver) {
            observer.unregister();
        }
        mContentObserver.clear();
    }

    public void onEvent(int event) {
        mUpdateHandler.removeMessages(event);
        mUpdateHandler.sendMessageDelayed(mUpdateHandler.obtainMessage(event, this), 1000);
    }

    static class UpdateHandler extends JUnitHandler<DownloadObserverImp> {
        @Override
        public void handleMessage(Message msg) {
            int event = msg.what;
            DownloadObserverImp downloadObserverImp = getMsgValue(msg.obj);
            downloadObserverImp.notifyContentChanged(event);
        }
    }
}
